import Contents from "../../components/contents/Contents";
import { useMemo, useEffect, useState, useRef } from "react";
import { getAllBuild } from "../../api/build";

import { addRoom, getAllRoom, delRoom, editRoom } from "../../api/room";
import {
  Space,
  Table,
  Tag,
  Button,
  Drawer,
  Form,
  Input,
  InputNumber,
  message,
  Popconfirm,
  Cascader,
  Radio,
} from "antd";
import { render } from "react-dom";
import { getAllType } from "../../api/roomType";

const RoomList = () => {
  const [data, setData] = useState([]);
  const [limit, setLimit] = useState(30); // 单页数量
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0); // 总数

  // 获取表格数据的主函数
  const getData = async () => {
    const postData = { limit, page };
    if (name) postData.name = name;
    if (price) postData.price = price;
   

    
    
    

    let res = await getAllRoom(postData);
    const { success, data, count } = res;

    if (success) {
     
      data.bandf = [postData.floor, postData.buildId];
        console.log(data);
      setData(data);
      setTotal(count);
    }
  };

  // 条件过滤
  const [name, setName] = useState("");
  const [price, setPrice] = useState("");

  useEffect(() => {
    getData();
  }, []);

  // 获取全部的楼栋信息
  const [build, setBuild] = useState([]);
  const getBuild = async () => {
    let res = await getAllBuild({});
    console.log("res", res);
    // 实际开发过程当中 得到的数据格式不一定符合我们的要求
    // 我们需要处理成我们要用的数据格式
    const temarr = res.data.map((item) => ({
      label: item.name,
      value: item._id,
      children: item.floorInfo.map((it) => ({ label: it, value: it })),
    }));
    setBuild(temarr);
  };

  useEffect(() => {
    getBuild(); // 获取楼栋信息
  }, []);

  const [type, setType] = useState([]);
  const getTypes = async () => {
    const res = await getAllType({ limit: 2000 });
    console.log("restypeall", res);
    setType(res.data.map((item) => ({ label: item.name, value: item._id })));
  };
  useEffect(() => {
    getTypes(); // 获取全部的房型信息
  }, []);

  const confirmDel = async (id) => {
    let res = await delRoom({ roomid: id });
    console.log(id)
    const { success } = res;
    if (!success) return message.warning("删除失败");
    message.success("删除成功");
    getData();
  };

  // 添加
  const formRef = useRef(null);
  // const [showAdd, setShowAdd] = useState(false);

  const [showAdd, setshowAdd] = useState(false);

  const [form1] = Form.useForm();
  const [form2] = Form.useForm();

  // 添加逻辑
  const handleAdd = async (a) => {
    console.log(a, "a");

    let values = form1.getFieldsValue(true);
    console.log(values); // 得到所有的表单的值
    let { bandf, type, ...postData } = values;
    console.log(postData, "postdata");
    type = type[0];
    let [buildId, floor] = bandf;
    let res = await addRoom({
      ...postData,
      floor,
      buildId,
      type,
    });
    const { success } = res;
    console.log(success);
    if (!success) return message.warning("添加失败");
    message.success("添加成功");
    getData(); // 刷新表格
    // formRef.current.reset(); // 重置表单
    form1.resetFields(); // 抽屉隐藏
    setshowAdd(false);
  };

  const [showEdit, setShowEdit] = useState(false);
  const [curRow, setcurRow] = useState(null);
  const edithandle = async (record) => {
    console.log(record);
    form2.setFieldsValue({
      ...record,
      bandf: [record.buildId, record.floor],
    });
    setcurRow(record);
  };

  // const a = async () => {
  //   const { bandf, ...postData } = values;
  //   const [buildId, floor] = bandf;
  //   // 发送请求执行修改
  //   let res = await editRoom({
  //     ...postData,
  //     roomid: curRow._id,
  //     buildId,
  //     floor,
  //   });
  //   const { success } = res;
  //   if (!success) return message.warning("修改失败");
  //   message.success("修改成功");
  //   getData(); // 刷新表格
  //   setShowEdit(false); // 抽屉隐藏
  // };

  const editFinish = async (values) => {
    // const values = form2.setFieldsValue(true); // 得到所有的表单的值
    console.log(values, "values");

    let {type, ...postData } = values;
     type = type[0];
   
    let [buildId, floor] = postData.bandf ?? [,];
 

    // 发送请求执行修改
    let res = await editRoom({
      ...postData,
      roomid: curRow._id,
      buildId,
      floor,
      type
    });
    const { success } = res;
    console.log("edit", success);
    if (!success) return message.warning("修改失败");
    message.success("修改成功");
    getData(); // 刷新表格
    setShowEdit(false); // 抽屉隐藏
  };

  //   const handlerDel = (id) => {
  //     const delDialog = DialogPlugin({
  //       header: "提醒",
  //       body: "你确定要删除当前的房型吗？",
  //       onConfirm: () => {
  //         delDialog.hide();
  //         confirmDel(id); // 执行删除
  //       },
  //       onClose: ({ e, trigger }) => {
  //         delDialog.hide();
  //       },
  //     });
  // };

 const onFinishFailed = () => {
   
   form1.setFieldsValue();
   form2.setFieldsValue();
   getData();
 };


  const cancel = (e) => {
    console.log(e);
    message.warning("无事发生");
  };

  const test = (a) => {
    console.log(a);
  };

  const columns = [
    {
      title: "房间名称",
      dataIndex: "roomName",
      name: "roomName",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "楼层",
      dataIndex: "floor",
      name: "floor",
    },
    {
      title: "是否有窗",
      dataIndex: "hasWindow",
      name: "hasWindow",
      render: (hasWindow) => {
        let color;
        let txt;
        if (hasWindow === true) {
          color = "green";
          txt = "是";
        } else {
          color = "red";
          txt = "否";
        }
        return <Tag color={color}>{txt}</Tag>;
      },
    },
    {
      title: "靠近马路",
      name: "isClose2Road",
      dataIndex: "isClose2Road",
      render: (isClose2Road) => {
        let color;
        let txt;
        if (isClose2Road === true) {
          color = "green";
          txt = "是";
        } else {
          color = "red";
          txt = "否";
        }
        return <Tag color={color}>{txt}</Tag>;
      },
    },
    {
      title: "允许吸烟",
      name: "isSmoke",
      dataIndex: "isSmoke",
      render: (isSmoke) => {
        let color;
        let txt;
        if (isSmoke === true) {
          color = "green";
          txt = "是";
        } else {
          color = "red";
          txt = "否";
        }
        return <Tag color={color}>{txt}</Tag>;
      },
    },
    {
      title: "高温房",
      name: "isHigh",
      dataIndex: "isHigh",
      render: (isHigh) => {
        let color;
        let txt;
        if (isHigh === true) {
          color = "green";
          txt = "是";
        } else {
          color = "red";
          txt = "否";
        }
        return <Tag color={color}>{txt}</Tag>;
      },
    },

    {
      title: "操作",
      name: "action",
      render: (record) => (
        <div>
          <Button
            style={{ marginRight: "10px" }}
            onClick={() => {
              return setShowEdit(true), edithandle(record);
            }}
          >
            修改
          </Button>
          <Popconfirm
            title="你确定是删除该房型吗?"
            onConfirm={() => confirmDel(record._id)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button>删除</Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const [pa, setpa] = useState({
    showSizeChanger: "true",
    total: total,
    pageSizeOptions: [5, 10, 20],
    defaultPageSize: 5,
    showTotal: (total) => `一共有${total}条数据`,
  });

  const Protable = () => (
    <Table
      columns={columns}
      dataSource={data}
      rowKey="_id"
      pagination={pa}
      onChange={setpa}
    />
  );

  return (
    <Contents title="房间管理">
      <div>
        <Button
          type="primary"
          style={{ margin: ".9375rem" }}
          onClick={() => setshowAdd(true)}
        >
          添加新的房间
        </Button>

        {/* <Input
            style={{ width: "150px", marginLeft: "250px" }}
            placeholder="输入你有查询的房型"
            onChange={(e) => setName(e.target.value)}
          />
          <Input
            style={{ width: "150px", marginLeft: "20px" }}
            placeholder="按价格查询"
            onChange={(e) => setPrice(e.target.value)}
          />
          <Button
            type="primary"
            style={{ margin: ".9375rem", float: "right" }}
            onClick={getData}
          >
            立即查询
          </Button> */}
      </div>

      <Protable></Protable>

      <Drawer visible={showAdd} width="600px" onClose={() => setshowAdd(false)}>
        <Form
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 14,
          }}
          onFinish={handleAdd}
          onFinishFailed={onFinishFailed}
          form={form1}
        >
          <Form.Item
            label="房间名称"
            name="roomName"
            required={true}
            initiaValues={build}
            rules={[
              {
                required: true,
                message: "请填写房间名称!",
              },
            ]}
          >
            <Input placeholder="填写房间名称" />
          </Form.Item>
          <Form.Item label="所在楼栋楼层" name="bandf">
            <Cascader options={build}></Cascader>
          </Form.Item>
          <Form.Item label="选择房型" name="type">
            <Cascader options={type}></Cascader>
          </Form.Item>
          <Form.Item label="内线电话" name="phone4in">
            <Input placeholder="请填写内线电话" />
          </Form.Item>
          <Form.Item label="外线电话" name="phone4out">
            <Input placeholder="请填写内线电话" />
          </Form.Item>
          <Form.Item label="方向朝向" name="direction" required={true}>
            <Radio.Group>
              <Radio.Button value="1">东</Radio.Button>
              <Radio.Button value="2">南</Radio.Button>
              <Radio.Button value="3">西</Radio.Button>
              <Radio.Button value="4">北</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否有窗户" name="hasWindow">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否靠近马路" name="isClose2Road">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否允许吸烟" name="isSmoke">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否是噪音房" name="isNoise">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否是高温房" name="isHigh">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Button
            htmlType="submit"
            type="primary"
            style={{ margin: ".625rem" }}
            // onClick={handleAdd}
          >
            确认提交
          </Button>
          <Button type="primary" onClick={() => setshowAdd(false)}>
            取消
          </Button>
        </Form>
      </Drawer>

      <Drawer
        visible={showEdit}
        width="600px"
        onClose={() => setShowEdit(false)}
      >
        <Form
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 14,
          }}
          onFinish={editFinish}
          onFinishFailed={onFinishFailed}
          form={form2}
        >
          <Form.Item
            label="房间名称"
            name="roomName"
            required={true}
            rules={[
              {
                required: true,
                message: "请填写房间名称!",
              },
            ]}
          >
            <Input placeholder="填写房间名称" />
          </Form.Item>
          <Form.Item label="所在楼栋楼层" name="bandf">
            <Cascader options={build}></Cascader>
          </Form.Item>
          <Form.Item label="选择房型" name="type">
            <Cascader options={type}></Cascader>
          </Form.Item>
          <Form.Item label="内线电话" name="phone4in">
            <Input placeholder="请填写内线电话" />
          </Form.Item>
          <Form.Item label="外线电话" name="phone4out">
            <Input placeholder="请填写内线电话" />
          </Form.Item>
          <Form.Item label="方向朝向" name="direction" required={true}>
            <Radio.Group>
              <Radio.Button value="1">东</Radio.Button>
              <Radio.Button value="2">南</Radio.Button>
              <Radio.Button value="3">西</Radio.Button>
              <Radio.Button value="4">北</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否有窗户" name="hasWindow">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否靠近马路" name="isClose2Road">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否允许吸烟" name="isSmoke">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否是噪音房" name="isNoise">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否是高温房" name="isHigh">
            <Radio.Group>
              <Radio.Button value={true}>是</Radio.Button>
              <Radio.Button value={false}>否</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Button
            htmlType="submit"
            type="primary"
            style={{ margin: ".625rem" }}
            // onClick={handleAdd}
          >
            确认修改
          </Button>
          <Button type="primary" onClick={() => setShowEdit(false)}>
            取消
          </Button>
        </Form>
      </Drawer>
    </Contents>
  );
};

export default RoomList;
